<template>
  <div class="app-container">

    <div class="role_table">
      <div class="filter-container">
        <el-button
          class="filter-item"
          style="margin: 10px;"
          type="primary"
          icon="el-icon-edit"
          @click="handleCreate"
        >
          添加角色
        </el-button>
      </div>
      <el-table
        v-loading="listLoading"
        :data="list"
        border
        fit
        highlight-current-row
        style="width: 100%;"
      >
        <el-table-column label="角色名称" min-width="80" align="center">
          <template slot-scope="{row}">
            <span>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="角色描述" min-width="100px" align="center">
          <template slot-scope="{row}">
            <span>{{ row.desc }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="330" class-name="small-padding fixed-width">
          <template slot-scope="{row,$index}">
            <el-button type="primary" size="mini" @click="handleUpdate(row)">
              编辑
            </el-button>
            <el-button size="mini" type="success" @click="handleMenuPermsEdit(row)">
              菜单权限
            </el-button>
            <el-button size="mini" type="success" @click="handleApiPermsEdit(row)">
              API 权限
            </el-button>
            <el-button size="mini" type="danger" @click="handleDelete(row,$index)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
        <el-form
          ref="dataForm"
          :rules="rules"
          :model="temp"
          label-position="left"
          label-width="100px"
          style="width: 400px; margin-left:50px;"
        >
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="temp.name" />
          </el-form-item>
          <el-form-item label="角色描述" prop="desc">
            <el-input v-model="temp.desc" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">
            取消
          </el-button>
          <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
            提交
          </el-button>
        </div>
      </el-dialog>

      <el-dialog title="设置菜单(路由)权限" :visible.sync="menuPermsDialogVisible">
        <el-form
          ref="menuPermsDialog"
          :model="menuPermstemp"
          label-position="left"
          label-width="100px"
          style="width: 400px; margin-left:50px;"
        >
          <el-form-item prop="name">
            <el-tree
              ref="menuPermsDialogTree"
              :check-strictly="checkStrictly"
              :data="menus"
              :props="defaultProps"
              :default-expand-all="true"
              show-checkbox
              node-key="_id"
              class="permission-tree"
            />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="handleMenuPermsDialogCancel">
            取消
          </el-button>
          <el-button type="primary" @click="handleMenuPermsDialogSubmit">
            提交
          </el-button>
        </div>
      </el-dialog>
      <el-dialog title="设置API权限" :visible.sync="apiPermsDialogVisible">
        <el-form
          ref="apiPermsDialog"
          :model="apiPermstemp"
          label-position="left"
          label-width="100px"
          style="width: 400px; margin-left:50px;"
        >
          <el-form-item prop="name">
            <el-tree
              ref="apiPermsDialogTree"
              :check-strictly="checkStrictly"
              :data="apis"
              :props="defaultProps"
              :default-expand-all="true"
              show-checkbox
              node-key="_id"
              class="permission-tree"
            />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="handleApiPermsDialogCancel">
            取消
          </el-button>
          <el-button type="primary" @click="handleApiPermsDialogSubmit">
            提交
          </el-button>
        </div>
      </el-dialog>
    </div>

  </div>
</template>

<script>
import { deepClone } from '@/utils'

const defaultRole = {
  title: '',
  _id: '',
  desc: ''
}
export default {
  data() {
    return {
      menuPermsDialogVisible: false,
      checkStrictly: false,
      menuPermstemp: {},
      role: Object.assign({}, defaultRole),
      menus: [],
      defaultProps: {
        children: 'children',
        label: 'title'
      },
      apiPermsDialogVisible: false,
      apiPermstemp: {},
      apis: [],
      list: [],
      total: 0,
      listLoading: true,
      temp: {
        _id: '',
        name: '',
        desc: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑角色',
        create: '创建角色'
      },
      rules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getList()
  },
  mounted() {
    this.getApis()
  },

  methods: {
    handleMenuPermsEdit(row) {
      this.menuPermsDialogVisible = true
      this.menuPermstemp = deepClone(row)
      this.$nextTick(() => {
        this.$api.getMenuTreeIncludeBtnApi().then(response => {
          this.menus = response.data.items
        })
        this.$refs.menuPermsDialogTree.setCheckedKeys(this.menuPermstemp.menuCheckedKeys)
      })
    },
    handleMenuPermsDialogCancel() {
      this.menus = []
      this.menuPermstemp = {}
      this.menuPermsDialogVisible = false
    },
    handleMenuPermsDialogSubmit() {
      const id = this.menuPermstemp._id
      const menuCheckedKeys = this.$refs.menuPermsDialogTree.getCheckedKeys()
      const menuHalfCheckedKeys = this.$refs.menuPermsDialogTree.getHalfCheckedKeys()
      const data = { id, menuCheckedKeys, menuHalfCheckedKeys }
      this.$api.updateRoleAssignMenuPermsApi(data).then(response => {
        this.getList()
        this.menus = []
        this.menuPermstemp = {}
        this.menuPermsDialogVisible = false
        this.$notify({
          title: 'Success',
          message: '设置菜单权限成功',
          type: 'success',
          duration: 2000
        })
      })
    },
    handleApiPermsEdit(row) {
      this.apiPermsDialogVisible = true
      this.apiPermstemp = deepClone(row)
      this.$nextTick(() => {
        this.$api.getApiListApi().then(response => {
          this.apis = response.data.items
        })
        this.$refs.apiPermsDialogTree.setCheckedKeys(this.apiPermstemp.apiCheckedKeys)
      })
    },
    handleApiPermsDialogCancel() {
      this.apis = []
      this.apiPermstemp = {}
      this.apiPermsDialogVisible = false
    },
    handleApiPermsDialogSubmit() {
      const id = this.apiPermstemp._id
      const apiCheckedKeys = this.$refs.apiPermsDialogTree.getCheckedKeys()
      const apiHalfCheckedKeys = this.$refs.apiPermsDialogTree.getHalfCheckedKeys()
      const data = { id, apiCheckedKeys, apiHalfCheckedKeys }
      this.$api.updateRoleAssignApiPermsApi(data).then(response => {
        this.getList()
        this.apis = []
        this.apiPermstemp = {}
        this.apiPermsDialogVisible = false
        this.$notify({
          title: 'Success',
          message: '设置菜单权限成功',
          type: 'success',
          duration: 2000
        })
      })
    },
    handleEdit(row) {
      this.dialogVisible = true

      this.role = deepClone(row)
      this.$nextTick(() => {
        this.$api.getMenuTreeIncludeBtnApi().then(response => {
          this.menus = response.data.items
        })
      })
    },
    getRoles() {
      this.$api.getMenuTreeIncludeBtnApi().then(response => {
        this.menus = response.data.items
      })
    },
    getApis() {
      this.$api.getApiListApi().then(response => {
        this.apis = response.data.items
      })
    },
    getList() {
      this.listLoading = true
      this.$api.getRoleListApi().then(response => {
        this.list = response.data.items
        this.total = response.data.total
        this.listLoading = false
      })
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    resetTemp() {
      this.temp = {
        _id: '',
        menus: [],
        name: ''
      }
    },
    createData() { // 添加角色
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.$api.createRoleApi(this.temp).then(() => {
            this.getList()
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: '角色添加成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          this.$api.updateRoleApi(tempData).then(() => {
            this.getList()
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Update Successfully',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row, index) {
      this.$api.removeRoleApi(row).then((data) => {
        this.getList()
        this.$notify({
          title: data.message,
          message: '',
          type: 'success',
          duration: 2000
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
